<template>
  <div class="salary-container">
    <div class="salary-search">
      <span class="page-title">工资明细列表</span>

      <el-input placeholder="请输入搜索内容" v-model="keyWords" class="input-with-select search-keyword">
        <el-select v-model="select" slot="prepend" placeholder="请选择">
          <el-option label="真实姓名" value=1></el-option>
          <el-option label="企业名称" value=2></el-option>
        </el-select>
      </el-input>
      <el-button type="primary" size="small" icon="el-icon-search" @click="searchSalary">搜索</el-button>
      <el-button type="info" size="small" class="search-keyword-reset" plain @click="resetSearch">重置</el-button>

      <el-button type="success" size="small" icon="el-icon-plus" @click="handelAdd"
                 v-if="checkPermissionPoints(1) == 1">
        新增
      </el-button>

      <el-button :type="multipleSelection.length > 0?'primary':'info'" size="small" icon="el-icon-edit"
                 @click="toggleSelection(salaryData)" style="margin-right: 10px">批量管理
      </el-button>
      <el-button type="info" size="small" plain @click="toggleSelection()" v-show="multipleSelection.length > 0">
        取消批量管理
      </el-button>

      <div class="excel-inout-box">
        <el-button type="warning" size="mini" icon="el-icon-search" @click="queryTotalMoney">查询目前导入总金额</el-button>

        <el-upload class="upload-demo upload-excel" action="#" :show-file-list="false" ref="uploadExcel"
                   accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"
                   :auto-upload="false" :limit="1" :on-change="handleImportExcel">
          <el-button :loading="downloadLoading" size="mini" type="info" plain icon="el-icon-folder-opened"
                     v-if="checkPermissionPoints(5) == 1">导入
          </el-button>
        </el-upload>

      </div>
    </div>

    <!--工资明细table-->
    <div class="salary-table">
      <el-table ref="multipleTable" :data="salaryData" border stripe fit :row-key="getRowKeys"
                @selection-change="handleSelectionChange" v-loading="listLoading"
                :default-sort="{prop: 'setTime', order: 'descending'}"
                @filter-change="filterChange" @sort-change='sortChange'
                :row-style="{height:'50px'}" :header-row-style="{height:'40px'}">
        <el-table-column type="selection" :reserve-selection="true" width="40"></el-table-column>
        <el-table-column label="ID" width="100">
          <template slot-scope="scope">
            <span>{{scope.row.id}}</span>
          </template>
        </el-table-column>
        <el-table-column label="真实姓名" width="120">
          <template slot-scope="scope">
            <span>{{scope.row.userName}}</span>
          </template>
        </el-table-column>
        <el-table-column label="注册手机号" width="150">
          <template slot-scope="scope">
            <span>{{scope.row.userTel}}</span>
          </template>
        </el-table-column>
        <el-table-column label="企业名称" width="320" show-overflow-tooltip>
          <template slot-scope="scope">
            <span>{{scope.row.mechanismName}}</span>
          </template>
        </el-table-column>
        <el-table-column label="工资金额" width="100">
          <template slot-scope="scope">
            <span>{{scope.row.money}}</span>
          </template>
        </el-table-column>
        <el-table-column label="工资月份" width="100">
          <template slot-scope="scope">
            <span>{{scope.row.time}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="setTime" label="状态最新时间" width="180" sortable>
          <template slot-scope="scope">
            <span v-if="scope.row.setTime">{{scope.row.setTime | formatTime}}</span>
          </template>
        </el-table-column>
        <el-table-column label="工资状态" width="120"
                         :filters="[{ text: '待领取', value: 1 }, { text: '已领取', value: 2 }, { text: '待确认', value: 3 }]"
                         :filter-multiple="false" column-key="status"
                         filter-placement="bottom-end" prop="status">
          <template slot-scope="scope">
            <span>{{scope.row.status | filterStatus}}</span>
          </template>
        </el-table-column>
        <el-table-column label="是否隐藏" width="100">
          <template slot-scope="scope">
            <span>{{scope.row.delStatus==0?'显示':'隐藏'}}</span>
          </template>
        </el-table-column>

        <el-table-column label="操作" min-width="200" fixed="right">
          <template slot-scope="{row}">
            <el-dropdown size="mini" :split-button="true" type="primary" @click="handleLook(row)"
                         v-if="checkPermissionPoints(3) == 1">查看
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item @click.native="handleEdit(row)" v-if="checkPermissionPoints(4) == 1">编辑
                </el-dropdown-item>
                <el-dropdown-item @click.native="handleDelete(row)" v-if="checkPermissionPoints(2) == 1">删除
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :type="2" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"
                  @pagination="getSalaryList" :totalGold="totalGold"/>
    </div>

    <!--查看-->
    <el-dialog title="详细信息" :visible.sync="dialogLookVisible" width="960px" class="salary-dialog look-dialog"
               top="11vh">
      <el-form label-position="right" size="medium" label-width="auto" class="demo-ruleForm">
        <el-form-item label="真实姓名：">
          <span>{{salary.userName}}</span>
        </el-form-item>
        <el-form-item label="工资详情：">
          <el-input type="textarea" disabled :autosize="{ minRows: 2}" style="width: 640px"
                    v-model="salary.salaryDetails" class="salary-desc-text"></el-input>
        </el-form-item>
        <el-form-item label="工资状态：">
          <span>{{salary.status| filterStatus}}</span>
        </el-form-item>
        <el-form-item label="是否隐藏：">
          <span>{{salary.delStatus==0?'显示':'隐藏'}}</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" style="width: 96px" @click="dialogLookVisible = false">取消</el-button>
      </div>
    </el-dialog>

    <!--新增/编辑-->
    <el-dialog :title="textMap[dialogStatus]" :lock-scroll="true" :visible.sync="dialogEditVisible" width="960px"
               top="11vh"
               class="salary-dialog" @close="cancelSalary">
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-position="right" size="medium" label-width="auto"
               class="demo-ruleForm">
        <el-form-item label="真实姓名：" v-if="dialogStatus == 'update'" prop="userName">
          <span>{{ruleForm.userName}}</span>
        </el-form-item>
        <el-form-item label="真实姓名：" v-else prop="userName">
          <el-input v-model="ruleForm.userName" style="width: 640px;" placeholder="请选择真实姓名" :disabled="true"
                    class="input-with-select" @click.native="openRealityView">
            <el-button slot="append" icon="el-icon-search"></el-button>
          </el-input>
        </el-form-item>
        <el-form-item label="工资详情：" prop="salaryDetails">
          <el-input type="textarea" v-model="ruleForm.salaryDetails" :autosize="{ minRows: 2}" style="width: 640px"
                    placeholder="请输入工资详情" class="salary-desc-text"></el-input>
        </el-form-item>
        <el-form-item label="工资状态：" prop="status">
          <el-radio-group v-model="ruleForm.status">
            <el-radio :label=1>待领取</el-radio>
            <el-radio :label=2>已领取</el-radio>
            <el-radio :label=3>待确认</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否隐藏：" prop="delStatus">
          <el-radio-group v-model="ruleForm.delStatus">
            <el-radio :label=0>显示</el-radio>
            <el-radio :label=1>隐藏</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" type="success" style="width: 96px" @click="saveOrSalary" :loading="sendLoad">保存
        </el-button>
        <el-button size="small" style="width: 96px" @click="cancelSalary">取消</el-button>
      </div>
    </el-dialog>

    <!--查询导入总金额-->
    <message-box :messageVisible="messageVisible" :goldNum="goldNum" @messageClose="messageClose"></message-box>

    <!--用户真实姓名-->
    <reality-name :realityView="realityView" @closeReality="closeReality" @selectReality="selectReality"></reality-name>
  </div>
</template>

<script>
  import {mapGetters} from 'vuex';
  import {permissionPoints} from '@/utils/permission';
  import Pagination from '@/components/Pagination';
  import {formatDate} from "@/utils/index";
  import MessageBox from '@/components/MessageBox';
  import RealityName from "@/components/common/realityName";
  import {
    addSalary,
    batchSalary, deleteSalary,
    getImportMoney,
    getInitSalaryList,
    getSalaryDetail, modifySalary
  } from "../../../api/finance/finance";
  import {getToken} from '@/utils/auth';

  export default {
    name: "salaryDetails",
    computed: {
      ...mapGetters([
        'points'
      ])
    },
    data() {
      return {
        downloadLoading: false,
        keyWords: '',
        select: '1',
        messageVisible: false,
        realityView: false,
        goldNum: 0,
        totalGold: 0,
        multipleSelection: [],
        total: 0,
        listLoading: false,
        listQuery: {
          page: 1,
          limit: 20,
          status: '',
          orderBy: 'set_time desc',
          userName: '',
          mechanismName: ''
        },
        salary: {},
        dialogLookVisible: false,
        dialogEditVisible: false,
        salaryData: [],
        salaryDesc: '',
        textMap: {
          update: '编辑',
          create: '新增'
        },
        dialogStatus: '',
        ruleForm: {
          userName: '',
          salaryDetails: '',
          status: 1,
          delStatus: 0,
          mechanismId: '',
          time: '',
          id: '',
          userId: ''
        },
        rules: {
          userName: [
            {required: true, message: '请选择真实姓名', trigger: 'change'}
          ],
          salaryDetails: [
            {required: true, message: '请输入工资详情', trigger: 'blur'}
          ],
          status: [
            {required: true, message: '请选择工资状态', trigger: 'change'}
          ],
          delStatus: [
            {required: true, message: '请选择是否隐藏', trigger: 'change'}
          ]
        },
        sendLoad: false
      }
    },
    created() {
      this.getSalaryList();
    },
    methods: {
      checkPermissionPoints(type) {
        let pointObj = this.points.salaryDetails;
        return permissionPoints(type, pointObj);
      },
      searchSalary() {//搜索
        if (this.keyWords == '' || this.keyWords == undefined) {
          return this.$message.info({message: '请输入搜索内容', duration: 1000});
        }
        this.listQuery.userName = '';
        this.listQuery.mechanismName = '';
        if (this.select == 1) {
          this.listQuery.userName = this.keyWords;
        } else if (this.select == 2) {
          this.listQuery.mechanismName = this.keyWords;
        }
        this.listQuery.page = 1;
        this.getSalaryList();
      },
      resetSearch() {
        this.select = '1';
        this.keyWords = '';
        this.listQuery.userName = '';
        this.listQuery.mechanismName = '';
        this.listQuery.status = '';
        this.$refs.multipleTable.clearFilter();
        this.$refs.multipleTable.clearSelection();
        this.listQuery.page = 1;
        this.getSalaryList();
      },
      getSalaryList() {//获取工资明细列表
        this.listLoading = true;
        getInitSalaryList(this.listQuery).then((res) => {
          this.listLoading = false;
          let retObj = res;
          if (retObj.code == 0 && retObj.data != null) {
            const {items, totalRecord, totalMoney} = retObj.data;
            this.total = totalRecord;
            this.salaryData = items;
            this.totalGold = totalMoney;
          }
        }).catch(() => {
          this.listLoading = false;
        })
      },
      filterChange(value) {//过滤
        this.listQuery.status = String(value.status);
        this.listQuery.page = 1;
        this.getSalaryList();
      },
      sortChange(column) {//排序
        if (column.prop == "setTime" && column.order == "ascending") {
          this.listQuery.orderBy = "set_time asc";
        } else if (column.prop == "setTime" && column.order == "descending") {
          this.listQuery.orderBy = "set_time desc";
        }
        this.listQuery.page = 1;
        this.getSalaryList();
      },
      queryTotalMoney() {//查询导入总金额
        this.messageVisible = true;
        getImportMoney().then((res) => {
          let retObj = res;
          if (retObj.code == 0 && retObj.data != null) {
            this.goldNum = retObj.data;
          }
        })
      },
      commonSelection() {
        let row = {};
        let value = this.multipleSelection;
        if (value && value.length > 0) {
          let arr = [];
          let num = [];
          value.forEach((item) => {
            arr.push(item.id);
            num.push(item.status);
          });
          row.id = arr.join(",");
          row.status = num;
        }
        return row;
      },
      messageClose() {
        this.messageVisible = false;
      },
      openRealityView() {
        this.realityView = true;
      },
      closeReality() {
        this.realityView = false;
      },
      selectReality(reality) {
        const {userId, userName} = reality;
        this.ruleForm.userId = userId;
        this.ruleForm.userName = userName;
        this.closeReality();
      },
      toggleSelection(rows) {
        if (rows) {
          if (this.multipleSelection.length > 0) {
            let selects = this.commonSelection();
            if (selects.status.includes(1) || selects.status.includes(2)) {
              return this.$alert('请勾选待确认的记录，再进行批量修改', '提示', {
                confirmButtonText: '确定',
                type: 'warning',
                callback: action => {}
              });
            }

            this.$confirm('确定将列表中勾选的记录修改为待领取？', '批量管理', {
              type: 'warning',
              confirmButtonText: '确定',
              cancelButtonText: '取消'
            }).then(() => {
              this.batchPass(selects);
            }).catch(() => {
              this.clearSelect();
            });
          }
        } else {
          this.clearSelect();
        }
      },
      clearSelect() {
        this.$refs.multipleTable.clearSelection();
        this.$refs.multipleTable.clearFilter();
        if (this.listQuery.status) {
          this.listQuery.status = '';
          this.listQuery.page = 1;
          this.getSalaryList();
        }
      },
      batchPass(selects) {
        batchSalary(selects.id).then((res) => {
          let retObj = res;
          if (retObj.code == 0 && retObj.data > 0) {
            this.$refs.multipleTable.clearSelection();
            this.$refs.multipleTable.clearFilter();
            this.listQuery.status = '';
            this.listQuery.page = 1;
            this.getSalaryList();
          }
        });
      },
      getRowKeys(row) {
        return row.id;
      },
      handleSelectionChange(val) {
        this.multipleSelection = val;
      },
      handleLook(row) {//详细信息
        this.dialogLookVisible = true;
        getSalaryDetail(row.id).then((res) => {
          let retObj = res;
          if (retObj.code == 0 && retObj.data != null) {
            this.salary = retObj.data;
          }
        })
      },
      handelAdd() {//新增
        this.dialogStatus = 'create';
        this.dialogEditVisible = true;
      },
      cancelSalary() {
        this.dialogEditVisible = false;
        this.$refs.ruleForm.resetFields();
      },
      handleEdit(row) {//编辑
        this.dialogStatus = 'update';
        this.dialogEditVisible = true;
        getSalaryDetail(row.id).then((res) => {
          let retObj = res;
          if (retObj.code == 0 && retObj.data != null) {
            this.ruleForm = retObj.data;
          }
        })
      },
      saveOrSalary() {//保存
        if (this.dialogStatus == 'create') {
          this.$refs.ruleForm.validate((valid) => {
            if (valid) {
              this.sendLoad = true;
              addSalary(this.ruleForm).then((res) => {//新增
                let retObj = res;
                this.sendLoad = false;
                if (retObj.code == 0 && retObj.data == 1) {
                  this.dialogEditVisible = false;
                  this.$refs.ruleForm.resetFields();
                  this.$message.success({message: '保存成功', duration: 2000});
                  this.getSalaryList();
                } else {
                  this.$message.error({message: '保存失败，请重试', duration: 2000});
                }
              }).catch(() => {
                this.sendLoad = false;
              })
            } else {
              return false;
            }
          });
        } else {
          this.$refs.ruleForm.validate((valid) => {
            if (valid) {
              this.sendLoad = true;
              let submitObj = {};
              submitObj.userName = this.ruleForm.userName;
              submitObj.salaryDetails = this.ruleForm.salaryDetails;
              submitObj.status = this.ruleForm.status;
              submitObj.delStatus = this.ruleForm.delStatus;
              submitObj.mechanismId = this.ruleForm.mechanismId;
              submitObj.time = this.ruleForm.time;
              submitObj.id = this.ruleForm.id;
              modifySalary(submitObj).then((res) => {//修改
                let retObj = res;
                this.sendLoad = false;
                if (retObj.code == 0 && retObj.data == 1) {
                  this.dialogEditVisible = false;
                  this.$refs.ruleForm.resetFields();
                  this.$message.success({message: '保存成功', duration: 2000});
                  this.getSalaryList();
                } else {
                  this.$message.error({message: '保存失败，请重试', duration: 2000});
                }
              }).catch(() => {
                this.sendLoad = false;
              })
            } else {
              return false;
            }
          });
        }
      },
      handleDelete(row) {//删除
        this.$confirm('此操作将删除该工资明细, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteSalary(row.id).then((res) => {
            let retObj = res;
            if (retObj.code == 0 && retObj.data > 0) {
              this.$message.success({message: '删除该工资明细成功', duration: 2000});
              this.getSalaryList();
            } else {
              this.$message.error({message: '删除该工资明细失败，请重试', duration: 2000});
            }
          })
        }).catch((err) => {
        });
      },
      handleImportExcel(file) {//导入
        let fd = new FormData();
        fd.append("file", file.raw);
        this.downloadLoading = true;

        this.axios.defaults.headers.common["tk"] = getToken();
        this.axios(
          {
            method: 'POST',
            url: '/lp_cms/salary/import_salary',
            data: fd,
            responseType: 'blob' //设置响应的数据类型为一个包含二进制数据的 Blob 对象，必须设置
          }
        ).then(res => {
          this.downloadLoading = false;
          if (res.status == 200) {
            if (res.headers && res.headers['content-disposition']) {
              const time = formatDate((new Date()), 'yyyy-MM-dd hhmmss');
              const blob = new Blob([res.data], {type: 'application/vnd.ms-excel'});
              const fileName = `工资明细错误序号表${time}.xls`;

              if (window.navigator && window.navigator.msSaveOrOpenBlob) {//兼容ie
                window.navigator.msSaveBlob(blob, fileName)
              } else {
                const linkNode = document.createElement('a');

                linkNode.download = fileName; //a标签的download属性规定下载文件的名称
                linkNode.style.display = 'none';
                linkNode.href = URL.createObjectURL(blob); //生成一个Blob URL
                document.body.appendChild(linkNode);
                linkNode.click();  //模拟在按钮上的一次鼠标单击

                URL.revokeObjectURL(linkNode.href); // 释放URL 对象
                document.body.removeChild(linkNode);
              }
            } else {
              const number = res.headers['num'];
              this.$message.success({message: `已成功导入${number}笔工资明细记录`, duration: 3500, offset: 350});
              this.getSalaryList();
            }
            this.$refs.uploadExcel.clearFiles();
          } else {
            this.$message.error({message: '网络异常', duration: 2000});
          }
        }).catch((err) => {
          this.$message.error(err);
        })
      }
    },
    filters: {
      formatTime(time) {
        let date = new Date(time);
        return formatDate(date, 'yyyy-MM-dd hh:mm:ss');
      },
      filterStatus(type) {
        if (type == 1) {
          return '待领取';
        } else if (type == 2) {
          return '已领取';
        } else if (type == 3) {
          return '待确认';
        }
      }
    },
    components: {
      RealityName,
      Pagination,
      MessageBox
    }
  }
</script>

<style lang="scss" scoped>
  .salary-container {
    .salary-search {
      display: flex;
      align-items: center;
      width: 100%;
      height: 80px;
      .page-title {
        padding-left: 20px;
        font-size: 18px;
        font-weight: bold;
        color: rgba(61, 68, 77, 1);
        min-width: 130px;
        text-align: left;
      }
      .search-keyword {
        margin-left: 36px;
        margin-right: 24px;
        width: 470px;
        > > > .el-select .el-input {
          width: 110px;
        }
        > > > .el-input-group__prepend {
          background-color: #fff;
        }
      }
      .search-keyword-reset {
        margin-right: 36px;
      }
      .button-position {
        margin-left: 30px;
      }
      .excel-inout-box {
        display: flex;
        margin-left: auto;
        margin-right: 18px;
        .upload-excel {
          margin-left: 8px;
        }
      }
    }
    .salary-table {
      width: 98%;
      margin-left: 18px;
      > > > .el-table td, .el-table th {
        padding: 6px 0px;
      }
      > > > .el-table__header th {
        padding: 0;
        height: 30px;
        line-height: 30px;
      }
      > > > .el-table__column-filter-trigger {
        line-height: 28px;
        i {
          font-size: 18px;
        }
      }
      > > > .el-table__row .cell {
        display: flex;
        align-items: center;
      }
      > > > .el-table__header .has-gutter .cell {
        display: flex;
        justify-content: space-between;
        align-items: center;
      }
      > > > .el-table__fixed-right {
        height: 100% !important;
      }
    }
    .salary-dialog > > > .el-dialog .el-dialog__header {
      display: flex;
      align-items: center;
      height: 48px;
      background: #F7F8FA;
      padding: 0px 0px 0px 12px;
      .el-dialog__headerbtn {
        top: 15px;
      }
    }
    .look-dialog > > > .el-form-item--mini.el-form-item, .el-form-item--small.el-form-item {
      margin-bottom: 0px;
    }
    .salary-dialog {
      font-size: 14px;
      color: #606266;
      .salary-desc-text > > > .el-textarea__inner {
        color: #333;
        font-size: 14px;
      }
      .input-with-select {
        > > > .el-input__inner {
          color: #333333;
        }
      }
    }
    > > > .el-button {
      line-height: 1.2;
    }
  }
</style>
